package com.llkj.qingnianguoxue.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.PayCartOrderAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.ExchangeBean;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.sevenheaven.iosswitch.ShSwitchView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayOrderActivity extends BaseActivity implements PayMethodViewUtil.PaySuccessListener{
    public static final int REQUEST_ORDER_PAY = 9989;//订单支付
    @BindView(R.id.rvShops)
    RecyclerView lvCart;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;//总价
    @BindView(R.id.tv_deduction_money)
    TextView tvDeduction;//抵扣
    @BindView(R.id.tv_pay_money)
    TextView tvActualMoney;//实际支付
    @BindView(R.id.sw_open)
    ShSwitchView swOpenBtn;//抵扣开关

    private PayCartOrderAdapter mOrderPayAdapter;//订单商品适配器
    private List<HotRankingBean.RankingBean> mShopCartData;
    private String mCheckedShopsId;
    private float mPrepareMoney,mActualMoney;//预支付金额,实际支付金额
    private PayMethodViewUtil payMethodViewUtil;
    private String mCategoryType;//判断来自哪个界面的支付
    private String mPayIntegral = "0",mDeductionMoney = "0";//兑换的积分数,抵扣金额

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_order);
        setTitle("订单支付", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        ButterKnife.bind(this);

        initView();
        userExchange();
    }

    private void initView(){
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        Intent intent = getIntent();
        mCategoryType = intent.getStringExtra("categoryType");
        mShopCartData = (List<HotRankingBean.RankingBean>) intent.getSerializableExtra("checkShops");
        mCheckedShopsId = intent.getStringExtra("shopsId");
        mPrepareMoney = intent.getFloatExtra("payMoney",0);
        tvTotalMoney.setText(String.format("%.2f",mPrepareMoney) + "银子");

        lvCart.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        mOrderPayAdapter = new PayCartOrderAdapter(R.layout.item_order_shops,mShopCartData);
        lvCart.setAdapter(mOrderPayAdapter);

        payMethodViewUtil = new PayMethodViewUtil(this,this);
        calculateAcrualMoney(false);
        swOpenBtn.setOn(false);
        swOpenBtn.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if(isOn){//抵扣
                    calculateAcrualMoney(true);
                }else{
                    calculateAcrualMoney(false);
                }
            }
        });
    }

    /**
     * 计算实际支付金额
     */
    private void calculateAcrualMoney(boolean isDeduction){
        mActualMoney = mPrepareMoney;
        if(isDeduction){//计算抵扣金额
            try{
                mActualMoney = mPrepareMoney-Float.parseFloat(mDeductionMoney);
            }catch (Exception e){
                mActualMoney = mPrepareMoney;
            }
        }
        tvActualMoney.setText(String.format("%.2f",mActualMoney) +"银子");
        if(Float.parseFloat(mDeductionMoney)<=0){
            tvDeduction.setText("物品金额未达到使用积分标准");
            tvDeduction.setTextColor(ContextCompat.getColor(this,R.color.colorFE4A49));
            swOpenBtn.setEnabled(false);
        }else{
            tvDeduction.setText(String.format(getString(R.string.course_deduction_money),mPayIntegral,mDeductionMoney));
        }

    }

    @OnClick({R.id.tv_pay})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_pay:
                payMethodViewUtil.showPayMethodDialog(String.valueOf(mActualMoney));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void paySucessResponse(int type) {
        //处理三方支付成功后的操作
        if(type!=1){//三方支付
            if("ViDeoDetail".equals(mCategoryType)){//视频购买
                buyShop("1",String.valueOf(type));
            }if("BookDetail".equals(mCategoryType)){//图书购买
                buyShop("2",String.valueOf(type));
            }else if("shopCart".equals(mCategoryType)){//购物车支付
                payCart("2");
            }
        }else{//余额
            String balance = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_BALANCE);
            if (StringUtils.isEmpty(balance) ||
                    Double.valueOf(balance) < Double.valueOf(mActualMoney)) {
                ToastUtil.makeLongText(this, "余额不足，请充值");
                startActivity(BalanceActivity.class);
                return;
            }
            if("ViDeoDetail".equals(mCategoryType)){//视频购买
                buyShop("1",String.valueOf(type));
            }if("BookDetail".equals(mCategoryType)){//图书购买
                buyShop("2",String.valueOf(type));
            }else if("shopCart".equals(mCategoryType)){//购物车支付
                payCart("1");
            }
        }
    }

    /**
     * 购买商品
     *type 1视频，2图书
     * @param way
     */
    private void buyShop(String type,String way) {
        loadWaitDialog();
        String is_integarl = swOpenBtn.isOn()?"2":"1";
        HttpMethod.orderVideo(this, this, String.valueOf(type), mCheckedShopsId, String.valueOf(mPrepareMoney), way,is_integarl,mPayIntegral);
    }

    private void payCart(String way){
        loadWaitDialog();
        String is_integarl = swOpenBtn.isOn()?"2":"1";
        HttpMethod.orderShopping(this, this, mCheckedShopsId, way, String.valueOf(mPrepareMoney),is_integarl,mPayIntegral);
    }

    private void userExchange(){
//        loadWaitDialog();
        HttpMethod.userExchange(this,this,String.valueOf(mPrepareMoney));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
         if(method == HttpMethod.HTTP_ORDER_ORDER_SHOPPING || method == HttpMethod.HTTP_ORDER_ORDER_VIDEO){//支付成功
            Intent intent = new Intent();
            intent.putExtra("result","sucess");
            setResult(RESULT_OK,intent);
            myFinish();
        }else if(method == HttpMethod.HTTP_ORDER_ORDER_SHOPPING){
             Intent intent = new Intent();
             intent.putExtra("result","sucess");
             setResult(RESULT_OK,intent);
             myFinish();
         }else if (method == HttpMethod.HTTP_PUB_USER_EXCHANGE) {//范儿币抵扣
             ExchangeBean exchangeBean = GsonUtil.GsonToBean(data,ExchangeBean.class);
             if(exchangeBean != null){
                 mPayIntegral = exchangeBean.getMax_integral();
                 mDeductionMoney = exchangeBean.getMax_exchange();
                 calculateAcrualMoney(false);
             }
         }
    }

    @Override
    protected void myToast() {
        super.myToast();
        ToastUtil.makeLongText(this,"购买成功");
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        dismissWaitDialog();
        if(method == HttpMethod.HTTP_ORDER_ORDER_SHOPPING || method == HttpMethod.HTTP_ORDER_ORDER_VIDEO){
            ToastUtil.makeLongText(this,"对不起，支付失败");
        }
    }
}
